package com.jonathan.sentinel.thread;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 *@ClassName SentinelExample
 *@Description 预热/冷启动方式
 *@Author wangl
 */
public class ThreadCONTROL_BEHAVIOR_WARM_UP {

    public static void main(String[] args) {
        initFlowRules();
        Stream.iterate(1, item -> item + 1).limit(20).forEach(a -> {
                    new Thread() {
                        @Override
                        public void run() {
                            for (int j = 0; j < 5; j++) {
                                //定义资源
                                try (Entry entry = SphU.entry("Hellothread")) {
                                    // 被保护的逻辑
                                    System.out.println("hello thread");
                                } catch (BlockException ex) {
                                    // 处理被流控的逻辑
                                    System.out.println("blocked!");
                                }
                            }
                        }
                    }.start();
                }
        );
    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
        //设置最大qps=20
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
